package com.yunyilian8.www.jokeapp.utils;

import android.text.TextUtils;
import android.text.format.Time;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @ProjectName: AndroidCommon
 * @FileName: DateTimeUtil.java
 * @CreateTime: 2014-2-8 下午3:49:26
 * @Author: Sammie.Zhang
 * @Description: 日期时间操作工具类
 */
public class DateTimeUtil {
    /**
     * Date对象转String
     *
     * @param date         Date对象
     * @param formatString 如:yyyy-MM-dd HH:mm:ss,sss
     * @return
     */
    public static String dateToString(Date date, String formatString) {
        String retStr = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatString);
            retStr = sdf.format(date);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return retStr;
    }

    /**
     * 把字符串转为时间
     *
     * @param strDate
     * @param formatStr
     * @return
     */
    public static Date strToDate(String strDate, String formatStr) {
        Date date = new Date();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
            date = sdf.parse(strDate);
        } catch (Exception e) {
            e.getMessage();
        }
        return date;
    }


    /**
     * 获取当前时间字符串
     *
     * @param formatString 如:yyyy-MM-dd HH:mm:ss,sss
     * @return
     */
    public static String getCurrentDateTimeString(String formatString) {
        SimpleDateFormat timeFormater = new SimpleDateFormat(formatString);// 日志内容的时间格式
        return timeFormater.format(new Date().getTime());
    }

    /**
     * 获取当前时间的Date对象
     *
     * @return
     */
    public static Date getCurrentDateObject() {
        return new Date(System.currentTimeMillis());
    }

    /**
     * 根据Date对象获取当前是星期几
     *
     * @param date
     * @return
     */
    public static String getWeekOfDate(Date date) {
        String[] weekDays = weekDays2;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK);
        if ((w - 1) < 0)
            w = 0;
        return weekDays[w - 1];
    }

    /**
     * 转换已有格式的日期字符的格式
     *
     * @param dateString 如:2014-01-02 10:10:10,100
     * @param formatStr  如:yyyy/MM/dd HH:mm:ss,sss
     * @return
     */
    public static String formatDateString(String dateString, String formatStr) {
        String dateTime = "";
        try {
            DateFormat format = new SimpleDateFormat(formatStr);
            Date date = format.parse(dateString);
            dateTime = dateToString(date, formatStr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dateTime;
    }

    /**
     * 長類型時間轉字符時間
     *
     * @param longDate
     * @param formatString
     * @return
     */
    public static String longToString(long longDate, String formatString) {
        Date date = new Date(longDate);
        return dateToString(date, formatString);
    }

    public static final String[] weekDays0 = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    public static final String[] weekDays1 = {"日", "一", "二", "三", "四", "五", "六"};
    public static final String[] weekDays2 = {"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

    /**
     * 根据Date对象获取当前是星期几
     *
     * @param date
     * @param type 0两个字 1一个字
     * @return
     */
    public static String getWeek(Date date, int type) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK);
        if ((w - 1) < 0)
            w = 0;
        String result = "";
        switch (type) {
            case 0:
                result = weekDays0[w - 1];
                break;
            case 1:
                result = weekDays1[w - 1];
                break;
            default:
                break;
        }
        return result;
    }


    /**
     * 通过两个时间段,获取两个时间段的间隔时间
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static Map<String, Long> getTimeSpace(long startTime, long endTime) {
        Map<String, Long> map = new HashMap<String, Long>();
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff = endTime - startTime;
        long day = diff / nd;// 计算差多少天
        long hour = diff % nd / nh;// 计算差多少小时
        if (diff % nd % nh > 0) {
            hour += 1;
        }
        long min = diff % nd % nh / nm;// 计算差多少分钟
        long sec = diff % nd % nh % nm / ns;// 计算差多少秒
        map.put("Day", day);
        map.put("Hour", hour);
        map.put("Min", min);
        map.put("Sec", sec);
        return map;
    }

    public static Map<String, Long> getTimeSpace(String startTime, String endTime, String format) {
        return getTimeSpace(strToDate(startTime, format).getTime(), strToDate(endTime, format).getTime());
    }


    public static String getOffsetMonth(Date protoDate, int monthOffset, String formatString) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(protoDate);
        cal.add(Calendar.MONTH, monthOffset); // 正确写法
        return dateToString(cal.getTime(), formatString);
    }

    public static Calendar CALENDAR = Calendar.getInstance();

    private DateTimeUtil() {
    }

    public static String getOffsetDayDate(Date protoDate, int dayOffset, String formatString) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(protoDate);
        cal.add(Calendar.DATE, dayOffset); // 正确写法
        return dateToString(cal.getTime(), formatString);
    }

    /**
     * 获取当前时间的字符串
     */
    public static String getNowDateStr() {
        return covertMillisToDateStr(System.currentTimeMillis());
    }

    ;

    /**
     * 获得日期
     *
     * @return yyyy年MM月dd日
     */
    public static String getDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        return df.format(CALENDAR.getTime());
    }

    /**
     * 获得星期几
     *
     * @return 星期几
     */
    public static String getWeek() {
        String str = "";
        switch (CALENDAR.get(Calendar.DAY_OF_WEEK)) {
            case 1:
                str = "星期日 ";
                break;
            case 2:
                str = "星期一 ";
                break;
            case 3:
                str = "星期二 ";
                break;
            case 4:
                str = "星期三 ";
                break;
            case 5:
                str = "星期四 ";
                break;
            case 6:
                str = "星期五 ";
                break;
            default:
                str = "星期六 ";
                break;
        }
        return str;
    }

    /**
     * 根据给定时间获得星期几
     *
     * @param dateTime
     * @return
     * @author OLH
     * @date 2013-9-10 下午3:45:50
     */
    public static String getWeek(long dateTime) {
        String str = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateTime);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        switch (dayOfWeek) {
            case 1:
                str = "日 ";
                break;
            case 2:
                str = "一 ";
                break;
            case 3:
                str = "二 ";
                break;
            case 4:
                str = "三 ";
                break;
            case 5:
                str = "四 ";
                break;
            case 6:
                str = "五 ";
                break;
            default:
                str = "六 ";
                break;
        }
        return str;
    }

    /**
     * 获取当前小时数
     *
     * @return int
     */
    public static int getHour() {
        return CALENDAR.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取分钟数
     *
     * @return int
     */
    public static int getMin() {
        return CALENDAR.get(Calendar.MINUTE);
    }

    /**
     * 获取当前时间
     *
     * @return 02：01
     */
    public static String getTime() {
        int hour = CALENDAR.get(Calendar.HOUR_OF_DAY);
        int min = CALENDAR.get(Calendar.MINUTE);
        StringBuilder stringBuilder = new StringBuilder();
        String ss = "AM";
        if (hour > 12) {
            hour -= 12;
            ss = "PM";
        }
        if (hour < 10)
            stringBuilder.append("0");
        stringBuilder.append(hour);
        stringBuilder.append(":");
        if (min < 10)
            stringBuilder.append("0");
        stringBuilder.append(min);
        stringBuilder.append(" ");
        stringBuilder.append(ss);
        return stringBuilder.toString();
    }

    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return yyyy-MM-dd
     */
    public static String formatDataToYMD(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return MM月dd日
     */
    public static String formatDateToMD(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("MM-dd-ss");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return yyyy年MM月dd日
     */
    public static String formatDateToYMD(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }


    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return yyyy年MM月dd日 HH:mm
     */
    public static String formatDataToYMDHM(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return yyyy年MM月dd日
     */
    public static String formatDataToYMDCN(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * 格式化时间
     *
     * @param timeMillis
     * @return yyyy年MM月
     */
    public static String formatDateToYM(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy年MM月");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * @param timeMillis
     * @return yyyy/MM/dd HH:mm
     */
    public static String formatRealTimeData(long timeMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        CALENDAR.setTimeInMillis(timeMillis);
        return formatter.format(CALENDAR.getTime());
    }

    /**
     * 转换字符串为Date类型
     *
     * @param str ：yyyy-MM-dd HH:mm，yyyy/MM/dd HH:mm
     * @return date
     */
    public static Date formatStrToDate(String str) {
        try {
            if (str.contains("-"))
                return formatStrToDate2(str);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            Date date = sdf.parse(str);
            return date;
        } catch (ParseException e1) {
            e1.printStackTrace();
            return new Date();
        }
    }

    public static Date formatStrToDate1(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    private static Date formatStrToDate2(String str) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = sdf.parse(str);
            return date;
        } catch (ParseException e1) {
            e1.printStackTrace();
            return new Date();
        }
    }

    /**
     * 将Long值的时间转换成标准日期格式
     *
     * @param millis
     * @return "yyyy-MM-dd HH:mm:ss"
     */
    public static String covertMillisToDateStr(long millis) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (millis > 0) {
            Date dt = new Date(millis);
            return sdf.format(dt);
        } else {
            return "1900-01-01 00:00:00";
        }
    }

    //

    /**
     * 将时间类型转换成毫秒
     *
     * @param date yyyy-MM-dd HH:mm:ss.SSS
     * @return long
     */
    public static long getdaytime(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date dt2 = null;
        try {
            dt2 = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dt2.getTime();
    }

    /**
     * 将结束时间戳距离开始时间戳的毫秒值转化成小时、分钟、秒数
     *
     * @param timeMs 结束时间戳距离开始时间戳的毫秒值
     * @return 00小时:00分:00秒
     */
    @SuppressWarnings("resource")
    public static String covertDiffMillisToTimeStr(long timeMs) {
        long totalSeconds = timeMs / 1000;// 获取文件有多少秒
        StringBuilder mFormatBuilder = new StringBuilder();

        Formatter formatter = new Formatter(mFormatBuilder, Locale.getDefault());
        int seconds = (int) totalSeconds % 60;
        int minutes = (int) (totalSeconds / 60) % 60;
        int hours = (int) totalSeconds / 3600;
        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%02d小时:%02d分:%02d秒", hours, minutes, seconds).toString();// 格式化字符串
        } else if (minutes > 0) {
            return formatter.format("%02d分:%02d秒", minutes, seconds).toString();
        } else {
            return formatter.format("%02d秒", seconds).toString();
        }
    }

    public static String covertDiffMillisToTimeStr2(long timeMs) {
        long totalSeconds = timeMs / 1000;// 获取文件有多少秒
        StringBuilder mFormatBuilder = new StringBuilder();

        Formatter formatter = new Formatter(mFormatBuilder, Locale.getDefault());
        int seconds = (int) totalSeconds % 60;
        int minutes = (int) (totalSeconds / 60) % 60;
        int hours = (int) totalSeconds / 3600;
        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();// 格式化字符串
        } else if (minutes > 0) {
            return formatter.format("%02d:%02d", minutes, seconds).toString();
        } else {
            return formatter.format("%02d", seconds).toString();
        }
    }

    /**
     * 获得服务端传回来的时间，
     * 可以解析【"/Date(1376530771673)/"】和【"2013-08-15T09:39:31.673"】这两种格式
     *
     * @return long型时间，当参数为空，返回Long.MIN_VALUE
     */
    public static long convertToLongByStr(String str) {
        try {
            if (str.contains("Date")) {//
                return Long.valueOf(str.substring(6, 19));
            } else if (str.contains("T")) {
                return getDayTimeToLongToSecondByStr(str.replace('T', ' ').toString());
            } else if (!TextUtils.isEmpty(str)) {
                return getDayTimeToLongToSecondByStr(str);
            }
            return Long.MIN_VALUE;
        } catch (Exception e1) {
            e1.printStackTrace();
            return Long.MIN_VALUE;
        }
    }

    /**
     * 将字符串dateStr(2013-01-31 08:59:49.42)转换成long型
     *
     * @param dateStr
     * @return long型，精确到毫秒
     */
    public static long getDayTimeToLongToSecondByStr(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt2 = null;
        try {
            dt2 = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dt2.getTime();
    }

    /**
     * JASON 时间字符串转化为时间戳
     *
     * @param jasonStr
     * @return
     */
    public static long getDateByJasonStr(String jasonStr) {
        int startIndex = jasonStr.indexOf("(");
        int endIndex = jasonStr.indexOf(")");
        if (startIndex > 0 && endIndex > 0) {
            long l = new Long(jasonStr.substring(startIndex + 1, endIndex));
            return l;
        }
        return Long.MIN_VALUE;
    }

    /**
     * 更换时间天数
     *
     * @param date
     * @param n
     * @return
     */
    public static long changeDay(long date, int n) {
        long endDate = 0;
        try {
            Calendar cd = Calendar.getInstance();
            cd.setTimeInMillis(date);
            cd.add(Calendar.DATE, n);// 增加一天
            return cd.getTimeInMillis();
        } catch (Exception e) {
            return endDate;
        }
    }

    /**
     * 判断指定日期是否过期
     *
     * @return
     */
    public static boolean compareDateToDate(Date compareDate, Date endDate) {
        if (compareDate.before(endDate)) {
            return false;
        }
        return true;
    }

    /**
     * 判断指定日期到当前时间是否过期
     *
     * @param date
     * @return
     */
    public static boolean compareDateToNow(String date) {
        if (TextUtils.isEmpty(date)) return false;
        Date cDate = null;

        try {
            cDate = strToDate(date, "yyyy-MM-dd HH:mm:ss");
            //    cDate = new Date(System.currentTimeMillis());//获取当前时间
        } catch (Exception e) {

        }
        if (null == cDate) return false;
        return compareDateToDate(cDate, new Date());
    }

    /**
     * 判断当前日期距离现在时间是不是24小时内
     *
     * @param date
     * @return 24小时内, 返回true 否则返回false
     */
    public static boolean isWithin24Hour(String date) {
        if (TextUtils.isEmpty(date)) return false;

        Date cDate = strToDate(date, "yyyy-MM-dd HH:mm:ss");

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(cDate); //数据进行类型转换
        calendar.add(Calendar.DATE, -1);

        return !compareDateToNow((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(calendar.getTime()));

    }

    /**
     * 判断指定日期到endDate是否过期
     *
     * @param compareDate 比较时间
     * @param endDate     到期时间
     * @return
     */
    public static boolean compareDateToDate(String compareDate, String endDate) {
        Date cDate = null;
        Date eDate = null;
        try {
            cDate = strToDate(compareDate, "yyyy-MM-dd hh:mm:ss");
            eDate = strToDate(endDate, "yyyy-MM-dd hh:mm:ss");
        } catch (Exception e) {
        }
        if (null == cDate || null == eDate) {
            return false;
        } else {
            return compareDateToDate(cDate, eDate);
        }

    }


    //获取两个时间的时间间隔字符串
    //例如：2016-06-05 12:00:00 ~ 2016-06-05 14:00:00
    //输出则为: 2016-06-05 12:00-14:00
    public static String getDateline(String date1, String date2) {
        String[] d1 = date1.split(" ");
        String[] d2 = date2.split(" ");
        if (d1.length != 2 || d2.length != 2) {
            return date1;
        }

        String[] h1 = d1[1].split(":");
        String[] h2 = d2[1].split(":");
        if (d1[0].equals(d2[0])) {
            return d1[0] + " " + h1[0] + ":" + h1[1] + "~" + h2[0] + ":" + h2[1];
        } else {
            return d1[0] + " " + h1[0] + ":" + h1[1] + "~" + d2 + " " + h2[0] + ":" + h2[1];
        }
    }

    //日期处理
    public static Map<String, String> handleDate(String date1, String date2, String format) {
        Map<String, String> result = new HashMap<String, String>(6);
        if (!TextUtils.isEmpty(date1)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(strToDate(date1, format));
            result.put("year", calendar.get(Calendar.YEAR) + "");
            result.put("month", formatInt(calendar.get(Calendar.MONTH) + 1));
            result.put("day", formatInt(calendar.get(Calendar.DAY_OF_MONTH)));
            result.put("week", weekDays1[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (calendar.get(Calendar.MINUTE) == 59) {
                hour += 1;
            }
            result.put("startHour", formatInt(hour));
        } else {
            result.put("year", "1990");
            result.put("month", "01");
            result.put("day", "01");
            result.put("week", "一");
            result.put("startHour", "00");
        }
        if (!TextUtils.isEmpty(date2)) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(strToDate(date2, format));
            int hour = calendar1.get(Calendar.HOUR_OF_DAY);
            if (calendar1.get(Calendar.MINUTE) == 59) {
                hour += 1;
            }
            result.put("endHour", formatInt(hour));
        } else {
            result.put("endHour", "00");
        }
        return result;
    }


    //日期处理2
    public static Map<String, String> handleDate1(String date1, String date2, String format) {
        Map<String, String> result = new HashMap<String, String>(6);
        if (!TextUtils.isEmpty(date1)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(strToDate(date1, format));
            result.put("year", calendar.get(Calendar.YEAR) + "");
            result.put("month", formatInt(calendar.get(Calendar.MONTH) + 1));
            result.put("day", formatInt(calendar.get(Calendar.DAY_OF_MONTH)));
            result.put("week", weekDays1[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            /*if (calendar.get(Calendar.MINUTE)==59){
                hour += 1;
            }*/
            int minute = calendar.get(Calendar.MINUTE);

            result.put("startHour", formatInt(hour));
            result.put("startMinute", formatInt(minute));
        } else {
            result.put("year", "1990");
            result.put("month", "01");
            result.put("day", "01");
            result.put("week", "一");
            result.put("startHour", "00");
        }
        if (!TextUtils.isEmpty(date2)) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(strToDate(date2, format));
            int hour = calendar1.get(Calendar.HOUR_OF_DAY);
            /*if (calendar1.get(Calendar.MINUTE)==59){
                hour += 1;
            }*/
            int minute = calendar1.get(Calendar.MINUTE);

            result.put("endHour", formatInt(hour));
            result.put("endMinute", formatInt(minute));
        } else {
            result.put("endHour", "00");
        }
        return result;
    }


    /**
     * 根据传入的字符串如(2.5),判断是不是一个整数,
     *
     * @param time
     * @return 是整数, 返回整数, 不是整数,+1返回.
     */
    public static int getPracticeHour(String time) {

        double v = Double.parseDouble(time);
        int b = (int) v;

        if (0 == v - (double) b) {
            // 整数
            return b;
        } else {
            return b + 1;
        }
    }


    //格式化数字转字符串
    public static String formatInt(int s) {
        if (s < 10 && s >= 0)
            return "0" + s;
        else
            return s + "";

    }

    /**
     * 获取当前日期的年份
     *
     * @return
     */
    public static int getYear() {
        Time time = new Time("GMT+8");
        time.setToNow();
        int year = time.year;
        return year;
    }

    /**
     * 获取当前日期的月份
     *
     * @return
     */
    public static int getMonth() {
        Time time = new Time("GMT+8");
        time.setToNow();
        int month = time.month + 1;
        return month;
    }

    /**
     * 获取当前日期的日
     *
     * @return
     */
    public static int getDay() {
        Time time = new Time("GMT+8");
        time.setToNow();
        int day = time.monthDay;
        return day;
    }

}
